<!-- Create by liu 2021/6/10 机构子项目列表 -->
<template>
  <div class="main_box">
    <el-row>
      <el-col :span="12"> </el-col>
    </el-row>

    <!-- 查询工具条 -->
    <el-row>
      <el-col :span="4">
        <InstitutionTree @institutionId="getInstitutionId"></InstitutionTree>
      </el-col>
      <el-col :span="20">
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="itemName">
              <el-input v-model="filters.itemName" clearable placeholder="子项目名称"></el-input>
            </el-form-item>
            <el-form-item prop="itemCode">
              <el-input v-model="filters.itemCode" clearable placeholder="子项目编号"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" id="searchButton" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="opration_wrap">
          <div>
            <el-tooltip content="刷新" placement="top">
              <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
            </el-tooltip>
            <el-tooltip content="返回" placement="top">
              <el-button circle icon="fa fa-mail-forward" @click="returnList()" size="mini"></el-button>
            </el-tooltip>
          </div>
          <div>
            <el-button type="primary" plain size="mini" icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()"> 新增</el-button>
            <el-button type="success" plain size="mini" icon="fa fa-plus" v-has="permissionImport" @click="handleClickImport()"> 导入</el-button>
            <el-button size="mini" plain type="info" icon="el-icon-folder" v-has="permissionExport" @click="handleClickExport()"> 导出</el-button>
          </div>
        </div>
      </el-col>
      <!-- 列表 -->
      <el-col :span="20" :xs="24" ref="tableRow">
        <el-table :data="dataList" :fit="true" highlight-current-row style="overflow-y: auto; max-height: 680px">
          <el-table-column type="index" width="50" align="center" label="序号"> </el-table-column>
          <el-table-column prop="subItemId" label="ID" width="100" align="center"></el-table-column>
          <el-table-column prop="subItemName" label="子项目名称" width="150"></el-table-column>
          <el-table-column prop="subItemCode" label="子项目编号" width="150"></el-table-column>
          <el-table-column prop="reportSubItemName" label="康来子项目名称" width="150"></el-table-column>
          <el-table-column prop="reportSubItemCode" label="康来子项目编号" width="150"></el-table-column>
          <el-table-column prop="subItemPrice" label="原价格" width="100" :formatter="formatPrice"></el-table-column>
          <el-table-column prop="subItemSalePrice" label="合作价格" width="100" :formatter="formatPrice"></el-table-column>
          <el-table-column prop="createUserName" label="创建人" width="90"></el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template slot-scope="scope">
              <span>
                <el-tag :type="formatStates(scope.row.state)" size="mini" effect="dark">
                  {{ formatState(scope.row.state) }}
                </el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="createDate" label="创建时间"></el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <!-- v-has="permissionCheck"  -->
              <el-button @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
                <el-dropdown-menu slot="dropdown">
                  <!--1.启用 0.禁用 -1.删除-->
                  <!-- v-has="permissionEdit"  -->
                  <el-dropdown-item v-if="scope.row.state === 1" @click.native="handleClickEditor(scope.row)">编 辑</el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.state === 0" @click.native="handleClickSuccess(scope.row, 1)">启 用</el-dropdown-item>
                  <!-- v-has="permissionDisable"  -->
                  <el-dropdown-item v-if="scope.row.state === 1" @click.native="handleClickDisable(scope.row, 0)">禁 用</el-dropdown-item>
                  <!-- v-has="permissionDelete"  -->
                  <el-dropdown-item v-if="scope.row.state === 0" @click.native="handleClickDelete(scope.row, -1)">删 除</el-dropdown-item>
                  <!-- <el-dropdown-item
                    disabled
                    v-if="scope.row.state === 0"
                    @click.native="handleIsDelete(scope.row)"
                    >删 除</el-dropdown-item
                  > -->
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页工具条 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNo"
          :page-sizes="[20, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, jumper, next, pager, prev"
          :total="page.pageTotal"
        ></el-pagination>
      </el-col>
    </el-row>

    <!--导入子项目Excel-->
    <uploadFile ref="uploadFile" @uploadFileList="getUploadFileList" :accept="uploadAccept" folder="institutionsub" :importTemplateUrl="importTemplateUrl"></uploadFile>
  </div>
</template>
<script>
import uploadFile from '@/components/UploadFile';
import * as message from '@/constants/message';
import InstitutionSelect from '@/components/InstitutionSelect';
import InstitutionTree from '@/components/InstitutionTree';
import InstitutionItemApi from '@/api/institution/institutionItem';
import UploadRecordApi from '@/api/system/uploadRecord';
import fileDownload from 'js-file-download';
import { INSTITUTION_SUB_ITEM_IMPORT_TEMPLATE } from '@/constants/constants.js';

export default {
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      importTemplateUrl: '', //导入模板的地址
      dataList: [],
      institutionId: '',
      institutionFindId: '',
      filters: {
        itemName: '',
        itemCode: '',
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      uploadAccept: 'all', // 上传的文件类型 0.all 1.pdf 2.img 3.video 4.excel
      uploadData: {
        uploadType: 5,
        fileDesc: '',
        uploadFile: '',
      },
      maxHeight: 680,
      permissionAdd: '',
      permissionImport: '',
      permissionExport: '',
      permissionCheck: '',
      permissionEdit: '',
      permissionSuccess: '',
      permissionDisable: '',
      permissionDelete: '',
    };
  },
  computed: {},
  components: {
    InstitutionSelect,
    InstitutionTree,
    uploadFile,
  },
  watch: {
    institutionFindId(val) {
      this.listData();
    },
  },
  mounted() {
    this.init();
  },
  created() {
    document.onkeydown = function (e) {
      let key = window.event.keyCode;
      if (key == 13) {
        document.getElementById('searchButton').click();
      }
    };
  },
  methods: {
    init() {
      let _this = this;
      _this.importTemplateUrl = INSTITUTION_SUB_ITEM_IMPORT_TEMPLATE; //获取导入模板的地址
      _this.getTableHeight();
      _this.dataList = [];
      if (this.$route.query.id) {
        this.institutionFindId = this.$route.query.id;
      } else {
        this.institutionFindId = localStorage.getItem('institutionIds');
      }
      this.listData();
    },

    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
      // this.onSearch();
    },
    formatPrice(row, column, cellValue) {
      // 价格过滤器
      if (!cellValue) {
        return '未知';
      } else {
        return cellValue + ' 元/次';
      }
    },
    getInstitutionId(val) {
      // 将组件中的id 附给搜索的按钮
      this.institutionFindId = val;
      localStorage.setItem('institutionIds', val);
    },
    // excel导入
    getUploadFileList(val) {
      ////debugger
      let _this = this;
      if (!val) {
        _this.$Utils.messageError('请选择文件上传');
        return;
      }
      _this.uploadData.uploadFile = val[0];
      _this.uploadData.fileDesc = 'EXCEL导入医检子项目信息';
      UploadRecordApi.addUploadRecord(_this.uploadData)
        .then((res) => {
          if (res.status == 0) {
            InstitutionItemApi.importExcelInstitutionSubItem({
              uploadId: res.data,
            }).then((res) => {
              _this.$Utils.notifySuccess();
              _this.listData();
            });
          } else {
            _this.$Utils.notifyError();
          }
        })
        .catch((error) => {
          _this.$Utils.notifyError('上传失败，请稍后重试');
        });
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickEditor(row) {
      // 编辑
      let _this = this;
      _this.$router.push({
        path: '/item/institutionSubItemAdd',
        query: { id: row.subItemId },
      });
    },
    handleClickSuccess(row, state) {
      // 启用
      let _this = this;
      let cond = {
        id: row.subItemId,
        state: state,
      };
      this.$confirm('是否启用该项目', message.TITLE_PROMPT).then(() => {
        InstitutionItemApi.updateInstitutionSubItemState(cond).then((res) => {
          _this.$message({
            type: 'success',
            message: '操作成功',
          });
          _this.listData();
        });
      });
    },
    handleClickDisable(row, state) {
      // 禁用
      let _this = this;
      let cond = {
        id: row.subItemId,
        state: state,
      };
      this.$confirm('是否禁用该项目', message.TITLE_PROMPT).then(() => {
        InstitutionItemApi.updateInstitutionSubItemState(cond).then((res) => {
          _this.$message({
            type: 'success',
            message: '操作成功',
          });
          _this.listData();
        });
      });
    },
    handleClickDelete(row, state) {
      // 删除
      let _this = this;
      let cond = {
        id: row.subItemId,
        state: state,
      };
      this.$confirm('是否删除该项目', message.TITLE_PROMPT).then(() => {
        InstitutionItemApi.updateInstitutionSubItemState(cond).then((res) => {
          _this.$message({
            type: 'success',
            message: '操作成功',
          });
          _this.listData();
        });
      });
    },
    // handleClickSuccess (row,state) {
    //   let _this = this
    //   this.$confirm("是否启用该项目", message.TITLE_PROMPT)
    //     .then(() => {
    //       _this
    //         .$Put(_this.$Config.api.institutionSubItemState, {
    //           id: row.subItemId,
    //           state: state
    //         })
    //         .then(res => {
    //           _this.$message({
    //             type: 'success',
    //             message: '操作成功'
    //           })
    //           _this.listData()
    //         })
    //         .catch(error => {
    //           _this.$notify.error({
    //             title: message.TITLE_ERROR,
    //             message: "操作失败，请稍后重试"
    //           })
    //         })
    //     })
    // },
    // handleClickDisable (row,state) {
    //   let _this = this
    //   this.$confirm("是否禁用该项目", message.TITLE_PROMPT)
    //     .then(() => {
    //       _this
    //         .$Put(_this.$Config.api.institutionSubItemState, {
    //           id: row.subItemId,
    //           state: state
    //         })
    //         .then(res => {
    //           _this.$message({
    //             type: 'success',
    //             message: '操作成功'
    //           })
    //           _this.listData()
    //         })
    //         .catch(error => {
    //           _this.$notify.error({
    //             title: message.TITLE_ERROR,
    //             message: "操作失败，请稍后重试"
    //           })
    //         })
    //     })
    // },
    // handleIsDelete(row) {
    //   let _this = this;
    //   this.$confirm("是否删除该项目", message.TITLE_PROMPT).then(() => {
    //     InstitutionItemApi.updateInstitutionSubItemState({
    //       id: row.subItemId
    //     }).then(res => {
    //       _this.$message({
    //         type: "success",
    //         message: "操作成功"
    //       });
    //       _this.listData();
    //     });
    //   });
    // },
    handleClickAdd() {
      // 新增
      let _this = this;
      _this.$router.push({
        path: '/item/institutionSubItemAdd',
        query: {
          institutionId: this.institutionFindId,
        },
      });
    },
    handleClickDetail(row) {
      // 查看
      let _this = this;
      _this.$router.push({
        path: '/item/institutionSubItemDetail',
        query: { id: row.subItemId },
      });
    },
    handleClickImport() {
      let _this = this;
      _this.uploadAccept = 'excel';
      _this.$refs.uploadFile.handleCreate();
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    listData() {
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
        institutionId: _this.institutionFindId,
        itemName: _this.filters.itemName,
        itemCode: _this.filters.itemCode,
      };
      InstitutionItemApi.listInstitutionSubItem(cond).then((res) => {
        _this.dataList = res.data.list;
        _this.page.pageTotal = res.data.total;
      });
    },
    formatState(cellValue) {
      if (cellValue == -1) {
        return '删除';
      } else if (cellValue == 0) {
        return '禁用';
      } else if (cellValue == 1) {
        return '启用';
      } else if (cellValue == 2) {
        return '待审核';
      }
    },
    formatStates(cellValue) {
      if (cellValue == -1) {
        return 'danger';
      } else if (cellValue == 0) {
        return 'info';
      } else if (cellValue == 1) {
        return 'success';
      } else if (cellValue == 2) {
        return '';
      }
    },
    // 导入
    handleClickImport() {
      let _this = this;
      _this.uploadAccept = 'excel';
      _this.$refs.uploadFile.handleCreate();
    },
    // excel导入
    getUploadFileList(val) {
      let _this = this;
      if (!val) {
        _this.$Utils.messageError('请选择文件上传');
        return;
      }
      _this.uploadData.uploadFile = val[0];
      _this.uploadData.fileDesc = 'EXCEL导入医检子项目信息';
      UploadRecordApi.addUploadRecord(_this.uploadData)
        .then((res) => {
          if (res.status == 0) {
            let params = {
              uploadId: res.data,
            };
            InstitutionItemApi.importSubItemExcel(params)
              .then((res) => {
                _this.$Utils.notifySuccess();
                _this.listData();
              })
              .catch((err) => {
                console.log(err, ' ReportItemApi.importItemExcel');
              });
          } else {
            _this.$Utils.notifyError();
          }
        })
        .catch((error) => {
          console.log(error, 'UploadRecordApi.addUploadRecord');
        });
    },

    // 导出
    handleClickExport() {
      let _this = this;
      _this
        .$confirm('此操作将导出excel文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        .then(() => {
          InstitutionItemApi.exportSubItemExcel({ institutionId: this.institutionFindId }).then((res) => {
            let date = new Date();
            fileDownload(res, `机构子项目表${date.getFullYear() + String(date.getMonth() + 1) + date.getDate()}.xlsx`);
          });
        });
    },
    returnList() {
      // this.$router.go(-1)
      this.$store.dispatch('delView', this.$route);
      this.$router.push('/items/institutionItemManagement');
    },
  },
};
</script>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
